package com.gaogzhen.dao;

import com.gaogzhen.domain.Account;
import com.gaogzhen.utils.JdbcUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Administrator
 * @date 2022-12-05 09:49
 */
public class AccountDao {
    public void out(Account out, BigDecimal money) throws SQLException {
        String sql = "update account set balance = balance - ? where id = ?";
        Connection conn = JdbcUtils.getConnection();
//        System.out.println(conn);
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setBigDecimal(1, money);
        preparedStatement.setInt(2, out.getId());
        preparedStatement.executeUpdate();
//        JdbcUtils.close(preparedStatement, conn);
    }

    public void in(Account in, BigDecimal money) throws SQLException {
        String sql = "update account set balance = balance + ? where id = ?";
        Connection conn = JdbcUtils.getConnection();
//        System.out.println(conn);
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setBigDecimal(1, money);
        preparedStatement.setInt(2, in.getId());
        preparedStatement.executeUpdate();
//        JdbcUtils.close(preparedStatement, conn);
    }

    public Account getById(Integer id) throws SQLException {
        String sql = "select * from Account where id = ?";
        Connection conn = JdbcUtils.getConnection();
//        System.out.println(conn);
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setInt(1, id);
        ResultSet resultSet = preparedStatement.executeQuery();
        Account account = null;
        if (resultSet != null) {
            account = new Account();
            resultSet.next();
            account.setId(resultSet.getInt("id"));
            account.setName(resultSet.getString("name"));
            account.setBalance(resultSet.getBigDecimal("balance"));
        }
//        JdbcUtils.close(preparedStatement, conn);
        return account;
    }

    public void close() {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JdbcUtils.close(conn);
    }
}
